﻿using MQTTnet.Client;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XiAnAirport.Models;
using static XiAnAirport.Startup;

namespace XiAnAirport.BUS.Mqtt
{
    public class MqttServerBUS
    {
        IMqttClient _mqttClient;
        IMqttClient _mqttShareClient;
        public MqttServerBUS()
        {
            FXMqttClient client = (FXMqttClient)ServicesLocator.Instance.GetService(typeof(FXMqttClient));
            this._mqttClient = client.MqttClient;
            //FXMqttShareClient share_client = (FXMqttShareClient)ServicesLocator.Instance.GetService(typeof(FXMqttShareClient));
            //this._mqttShareClient = share_client.MqttShareClient;
        }


        public async Task<ResponseMessage> PublicAsyncMessage(string Topic, string Message, int QuantityOfLevel)
        {
            ResponseMessage message = new ResponseMessage() { errcode = 0, errmsg = "", data = null };
            try
            {
                await this._mqttClient.PublishAsync(new MQTTnet.MqttApplicationMessage()
                {
                    Payload = UTF8Encoding.UTF8.GetBytes(Message),
                    QualityOfServiceLevel = (MQTTnet.Protocol.MqttQualityOfServiceLevel)QuantityOfLevel,
                    Topic = Topic,
                    Retain = false,
                }).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                LogHelper.Log("发送锁梯异常" + e.ToString());

                message.errcode = 1;
                message.errmsg = $"发送{Topic}主题错误";
                return message;
            }
            return message;
        }

        public async Task<ResponseMessage> SendShareMessage(string Topic, string Message, int QuantityOfLevel)
        {
            ResponseMessage message = new ResponseMessage() { errcode = 0, errmsg = "", data = null };
            try
            {
                await this._mqttShareClient.PublishAsync(new MQTTnet.MqttApplicationMessage()
                {
                    Payload = UTF8Encoding.UTF8.GetBytes(Message),
                    QualityOfServiceLevel = (MQTTnet.Protocol.MqttQualityOfServiceLevel)QuantityOfLevel,
                    Topic = Topic
                }).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                LogHelper.MqttLog(e.ToString());

                message.errcode = 1;
                message.errmsg = $"发送{Topic}主题错误";
                return message;
            }
            return message;
        }
    }
}
